package com.wu.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {

	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String urlString) {
		String body = "";
		HttpURLConnection httpUrlConn = null;
		InputStreamReader inputStreamReader = null;
		// System.out.println(monitorInfo.getDomainUrl()+"====");
		try {
			URL url = new URL(urlString);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setRequestProperty("Accept-Charset", "utf-8");
			httpUrlConn.setRequestProperty("Content-Type", "application/json");
			httpUrlConn.setRequestProperty("Connection", "keep-alive");
			httpUrlConn.setDoOutput(true); // http正文内，因此需要设为true, 默认情况下是false;
			httpUrlConn.setDoInput(true); // 设置是否从httpUrlConnection读入，默认情况下是true;
			httpUrlConn.setUseCaches(false); // Post 请求不能使用缓存
			httpUrlConn.setRequestMethod("GET");
			httpUrlConn.connect();
			// 将返回的输入流转换成字符串
			inputStreamReader = new InputStreamReader(httpUrlConn.getInputStream(), "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			body = buffer.toString();
			// String gbkStr = new String(body.getBytes("ISO8859-1"),"UTF-8");
			// body=decodeUnicode(body);
			// System.out.println(body);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				inputStreamReader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return body;
	}

	public static String sendPost(String urlString) {
		String body = "";
		HttpURLConnection httpUrlConn = null;
		InputStreamReader inputStreamReader = null;
		// System.out.println(monitorInfo.getDomainUrl()+"====");
		try {
			URL url = new URL(urlString);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setRequestProperty("Accept-Charset", "utf-8");
			httpUrlConn.setRequestProperty("Content-Type", "application/json");
			httpUrlConn.setRequestProperty("Connection", "keep-alive");
			httpUrlConn.setDoOutput(true); // http正文内，因此需要设为true, 默认情况下是false;
			httpUrlConn.setDoInput(true); // 设置是否从httpUrlConnection读入，默认情况下是true;
			httpUrlConn.setUseCaches(false); // Post 请求不能使用缓存
			httpUrlConn.setRequestMethod("POST");
			httpUrlConn.connect();
			// 将返回的输入流转换成字符串
			inputStreamReader = new InputStreamReader(httpUrlConn.getInputStream(), "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			body = buffer.toString();
			// String gbkStr = new String(body.getBytes("ISO8859-1"),"UTF-8");
			// body=decodeUnicode(body);
			// System.out.println(body);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				inputStreamReader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return body;
	}

	public static String sendGetIO(String urlString) {
		String body = "";
		HttpURLConnection httpUrlConn = null;
		InputStreamReader inputStreamReader = null;
		// System.out.println(monitorInfo.getDomainUrl()+"====");
		try {
			URL url = new URL(urlString);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setRequestProperty("Accept-Charset", "utf-8");
			httpUrlConn.setRequestProperty("Content-Type", "application/json");
			httpUrlConn.setRequestProperty("Connection", "keep-alive");
			httpUrlConn.setDoOutput(true); // http正文内，因此需要设为true, 默认情况下是false;
			httpUrlConn.setDoInput(true); // 设置是否从httpUrlConnection读入，默认情况下是true;
			httpUrlConn.setUseCaches(false); // Post 请求不能使用缓存
			httpUrlConn.setRequestMethod("GET");
			httpUrlConn.connect();
			// 将返回的输入流转换成字符串
			inputStreamReader = new InputStreamReader(httpUrlConn.getInputStream(), "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
				System.out.println(buffer);
			}
			File videoFile = new File("d:/2.mp4");

			FileOutputStream outStream = new FileOutputStream(videoFile);

			outStream.write(buffer.toString().getBytes());

			outStream.close();

			// body=buffer.toString();
		} catch (Exception e) {
			// TODO: handle exception
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				inputStreamReader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return body;
	}

	public static String decodeUnicode(String theString) {

		char aChar;

		int len = theString.length();

		StringBuffer outBuffer = new StringBuffer(len);

		for (int x = 0; x < len;) {

			aChar = theString.charAt(x++);

			if (aChar == '\\') {

				aChar = theString.charAt(x++);

				if (aChar == 'u') {

					// Read the xxxx

					int value = 0;

					for (int i = 0; i < 4; i++) {

						aChar = theString.charAt(x++);

						switch (aChar) {

						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException("Malformed   \\uxxxx   encoding.");
						}

					}
					outBuffer.append((char) value);
				} else {
					if (aChar == 't')
						aChar = '\t';
					else if (aChar == 'r')
						aChar = '\r';

					else if (aChar == 'n')

						aChar = '\n';

					else if (aChar == 'f')

						aChar = '\f';

					outBuffer.append(aChar);

				}

			} else

				outBuffer.append(aChar);

		}

		return outBuffer.toString();

	}

	public static String Unicode(final String dataStr) {
		int start = 0;
		int end = 0;
		final StringBuffer buffer = new StringBuffer();
		while (start > -1) {
			end = dataStr.indexOf("\\u", start + 2);
			String charStr = "";
			if (end == -1) {
				charStr = dataStr.substring(start + 2, dataStr.length());
			} else {
				charStr = dataStr.substring(start + 2, end);
			}
			char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
			buffer.append(new Character(letter).toString());
			start = end;
		}
		return buffer.toString();
	}

	public static void download(String urlString, String filename, String savePath) throws Exception {
		File sf = new File(savePath +File.separator + filename);
		if (!sf.exists()) {

			// 构造URL
			URL url = new URL(urlString);
			// 打开连接
			URLConnection con = url.openConnection();
			// 设置请求超时为5s
			con.setConnectTimeout(5 * 1000);
			// 输入流
			InputStream is = con.getInputStream();

			// 1K的数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			// 输出的文件流
			sf = new File(savePath);
			if (!sf.exists()) {
				sf.mkdirs();
			}
			OutputStream os = new FileOutputStream(sf.getPath() + File.separator + filename);
			// 开始读取
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			// 完毕，关闭所有链接
			os.close();
			is.close();
		}
	}
	
	public static List getCookie(String loginAction) throws Exception{  
        //登录  
        URL url = new URL(loginAction);  
       // String param = "username="+username+"&password="+password;  
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
        conn.setRequestProperty("Accept-Charset", "utf-8");
        conn.setRequestProperty("Content-Type", "application/json");
		conn.setRequestProperty("Connection", "keep-alive");
		conn.setDoOutput(true); // http正文内，因此需要设为true, 默认情况下是false;
		conn.setDoInput(true); // 设置是否从httpUrlConnection读入，默认情况下是true;
		conn.setUseCaches(false); // Post 请求不能使用缓存
		conn.setRequestMethod("GET");
        conn.connect();
		InputStreamReader inputStreamReader = null;
		// 输入流
		InputStream is = conn.getInputStream();
				
        	// 1K的数据缓冲
		//System.out.println(is.available());
     			//byte[] bs = new byte[4096];
     			// 读取到的数据长度
     			// 开始读取
     			//System.out.println(is.read());
     			//is.read(bs);
     			//OutputStream os = new FileOutputStream("d:\\1.jpg");
     			//os.write(bs);
     			//os.flush();
     			//os.close();
//     			while ((len = is.read(bs)) != -1) {
//    				os.write(bs, 0, len);
//    			}
     			
     			ByteArrayOutputStream output = new ByteArrayOutputStream();
    		    byte[] buffer = new byte[1024];
    		    int n = 0;
    		    while (-1 != (n = is.read(buffer))) {
    		        output.write(buffer, 0, n);
    		    }
    		    
    		    buffer=output.toByteArray();
    		    
    		    
        List sessionId = new ArrayList();  
        String cookieVal = "";  
        String key = null;  
        sessionId.add(buffer);
        
        is.close();
        //取cookie  
        for(int i = 1; (key = conn.getHeaderFieldKey(i)) != null; i++){  
        	
            if(key.equalsIgnoreCase("Set-Cookie")){  
            	//System.out.println(key.toString()+"="+conn.getHeaderField("Set-Cookie").toString());
                cookieVal = conn.getHeaderField(i);  
                cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));  
                sessionId.add(cookieVal);  
            }  
        }  
        return sessionId;  
    }  
}
